package com.hzhc.controller.sysmanage;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzhc.common.BaseController;
import com.hzhc.entity.SysMsgNotify;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.service.PushService;
import com.hzhc.service.SysMsgNotifyService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.utils.TokenUtil;
import com.hzhc.vo.SysMsgNotifyVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author dongcy
 * @date 2024/9/3 9:09
 * @description SysMsgNotifyController   场站消息提醒
 */
@RestController
@RequestMapping("/sysMsgNotify")
@RequiredArgsConstructor
public class SysMsgNotifyController extends BaseController {

    private final SysMsgNotifyService msgNotifyService;

    private final PushService pushService;

    @Value("${cms.targetUrl}")
    private String url;

    /**
     * 消息提醒 list
     * @param request
     * @param vo
     * @return
     */
    @RequestMapping("/getList")
    public ResultUtil<List<SysMsgNotifyVo>> getList(HttpServletRequest request, @RequestBody SysMsgNotifyVo vo){
        Long userID = TokenUtil.getUserID(request);
        vo.setUserId(userID.intValue());
        Page<SysMsgNotifyVo> page = new Page<>(vo.getPageIndex(),vo.getPageSize());
        List<SysMsgNotifyVo> list = msgNotifyService.getCmsList(page,vo);
        return ResultUtil.build(list,page.getTotal(),page.getPages(), ResultUtilCodeEnum.SUCCESS);
    }

    /**
     * 右上角点击 修改为已读
     * @param request
     * @param notify
     * @return
     */
    @RequestMapping("/updateReadState")
    public ResultUtil<T> updateReadState(HttpServletRequest request,@RequestBody SysMsgNotify notify){
        return msgNotifyService.updateReadState(notify);
    }

    //推送WebSocket消息
    @RequestMapping("/toWebSocketMsg")
    public void toWebSocketMsg(@RequestBody List<SysMsgNotifyVo> vo){

        for (SysMsgNotifyVo notify : vo) {
            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg",notify.getMsg());//消息内容
            webSocketMsg.put("type",notify.getType());//业务审核
            webSocketMsg.put("id",notify.getId());//
            webSocketMsg.put("url",notify.getUrl());
            webSocketMsg.put("urlId",notify.getUrlId());
            webSocketMsg.put("title",notify.getTitle());
//            webSocketMsg.put("targetUserId",notify.getTargetUserId());
            //推送至websocket
            pushService.pushMsgToOne(notify.getTargetUserId(),webSocketMsg.toJSONString());

        }


    }

}
